import router from "./router";
import store from "./store";
import NProgress from "nprogress"; // progress bar
import "nprogress/nprogress.css"; // progress bar style
import { getToken, setToken } from "@/utils/auth"; // get token from cookie
import getPageTitle from "@/utils/get-page-title";
import { getLastDomain } from "@/utils/common"; // get token from cookie

NProgress.configure({ showSpinner: false }); // NProgress Configuration

router.beforeEach(async (to, from, next) => {
  setToken(sessionStorage.getItem("token"));
  //开始进度条
  NProgress.start();

  // set page title
  document.title = getPageTitle(to.meta.title);
  if (to.path === "/dashboard") {
    if (!!to.query.token && !!to.query.id) {
      next();
      sessionStorage.setItem("token", to.query.token);
      sessionStorage.setItem("subId", to.query.id);
      store.commit("user/SET_TOKEN", to.query.token);
      await store.dispatch("user/getInfo");
      await store.dispatch("permission/generateRoutes", {
        appId: sessionStorage.getItem("subId")
      });
      NProgress.done();
    } else {
      if (!!getToken().length && getToken() !== 'null') {
        next();
      } else {
        sessionStorage.clear();
        window.location.href = getLastDomain();
      }
    }
  } else {
    next();
  }

});

router.afterEach(() => {
  //完成进度条 
  NProgress.done();
});
